package com.gimi.cloud.bbp.app.consumer.service.mall.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.bbp.app.consumer.feign.mall.MallCartFeignService;
import com.gimi.cloud.bbp.app.consumer.service.mall.MallCartService;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.reqhead.Util;
import com.gimi.cloud.bbp.dto.mall.MallCartDTO;

@Service
public class MallCartServiceImpl implements MallCartService{
	@Autowired MallCartFeignService mallCartFeignService;

	@Override
	public void addGoodsToShoppingCart(String requestData, HttpServletRequest request, HttpServletResponse response) {
		MallCartDTO mallCart = null;
		try {
			mallCart = JSON.parseObject(requestData,MallCartDTO.class);
		} catch (Exception e) {
			throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR,"参数未知错误，请检查请求参数");
		}
		
		if (mallCart.getSkuId()==null) {
			throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR,"单品ID不能为空");
		}
		mallCart.setUserId(Integer.valueOf(request.getHeader("userId")));
		Util.sendResponse(mallCartFeignService.addGoodsToShoppingCart(mallCart), response);
	}

	@Override
	public void showShoppingCart(String requestData, HttpServletRequest request, HttpServletResponse response) {
		MallCartDTO mallCart = JSON.parseObject(requestData,MallCartDTO.class);
		mallCart.setUserId(Integer.valueOf(request.getHeader("userId")));
		Util.sendResponse(mallCartFeignService.showShoppingCart(mallCart), response);
	}

	@Override
	public void updateShoppingCart(String requestData, HttpServletRequest request, HttpServletResponse response) {
		MallCartDTO mallCart = JSON.parseObject(requestData,MallCartDTO.class);
		if (mallCart.getSkuId()==null) {
			throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR,"单品ID不能为空");
		}
		mallCart.setUserId(Integer.valueOf(request.getHeader("userId")));
		Util.sendResponse(mallCartFeignService.updateShoppingCart(mallCart), response);
	}

	@Override
	public void deleteShoppingCart(String requestData, HttpServletRequest request, HttpServletResponse response) {
        JSONObject parseObject = JSON.parseObject(requestData);
        parseObject.put("userId", request.getHeader("userId"));
        Object cartIdList = parseObject.get("cartIdList");
        if (cartIdList==null) {
        	throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR,"购物车ID列表不能为空");
		}
        if (!(cartIdList instanceof JSONArray)) {
        	throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR,"购物车ID列表格式错误，不是一个正确的列表");
		}
		Util.sendResponse(mallCartFeignService.deleteShoppingCart(parseObject), response);
	}
}